package com.zut.dao.impl;

import com.zut.dao.ClassesDao;
import com.zut.entity.Classes;
import com.zut.util.JdbcUtil;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 * 班级的持久层实现类：操作班级表
 */
public class ClassesDaoImpl implements ClassesDao {

    //获取JdbcTemplate
    private JdbcTemplate template = JdbcUtil.template;

    /**
     * 根班级名称查询班级
     * @param classesName
     * @return
     */
    @Override
    public Classes findClassByName(String classesName) {

        try {
            String sql = "select * from classes where name=?";
            return template.queryForObject(sql, new BeanPropertyRowMapper<>(Classes.class), classesName);
        }catch (EmptyResultDataAccessException e){
            return null;
        }

    }

    /**
     * 添加班级信息
     * @param classesName
     */
    @Override
    public void addClasses(String classesName) {
        String sql = "insert into classes values(null,?)";
        template.update(sql,classesName);
    }

    /**
     * 查询班级表中的所有数据
     * @return
     */
    @Override
    public List<Classes> findAllClasses() {
        return template.query("select * from classes",new BeanPropertyRowMapper<>(Classes.class));
    }

    /**
     * 根据名称模糊查询
     * @param className
     * @return
     */
    @Override
    public List<Classes> findClassByClassName(String className) {
        String sql = "select * from classes where name like ?";
        return template.query(sql, new BeanPropertyRowMapper<>(Classes.class), className);
    }

    /**
     * 修改sql
     * @param classId
     * @param newClassName
     * @return
     */
    @Override
    public int updateClassName(String classId, String newClassName) {
        String sql = "update classes set name=? where id=?";

        return template.update(sql,newClassName,classId);
    }

    /**
     * 删除表中班级
     * @param classId
     * @return
     */
    @Override
    public int deleteClasses(String classId) {
        return template.update("delete from classes where id=?",classId);
    }

    /**
     * 添加教授班级的关系
     * @param tid
     * @param classId
     */
    @Override
    public void addTeachingClass(String tid, String classId) {
        String sql = "insert into teachingClass values(null,?,?)";
        template.update(sql,tid,classId);

    }


}
